// pages/groupchat/groupchat/groupchat.js
let app = getApp().globalData
import {
  debounce,
  splitBase64IntoChunks
} from "../../../utils/util"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    chatName: "20计科1班(47)", //群聊名字加人数
    chat_ID: null, //当前群聊id
    chatHeight: null, //底部高
    optHeightRpx: null,
    create_id:null,//群主id
    key_value: null, //输入框的值
    scrollToBottom: null, //滚动到底部的距离
    func_transilate: 400,
    socket: null,
    chat_num: null, //群号
    chatRecords: [], //聊天记录
    userId: null,
    isRefreshing: true,
    page: {
      pageNum: 2,
      pageSize: 10
    },
    // 发送图片的地址
    uploadUrl: null,
    sendImgUrl: null
  },
  onChange: debounce(function (e) {
    this.setData({
      key_value: e.detail
    })
  }, 100),
  onFocus(e) {
    let rep = 750 / app.systemInfo.windowWidth * e.detail.height
    this.setData({
      chatHeight: rep,
      func_transilate: 400,
    })
  },
  onBlur() {
    if (this.data.func_transilate == 0) {
      this.setData({
        chatHeight: 400,
      })
      return
    }
    this.setData({
      chatHeight: 0,
    })
  },
  onClickClose() {
    this.setData({
      chatHeight: 0,
      func_transilate: 400
    })
  },
  // 编辑群聊
  to_edit_class() {
    wx.navigateTo({
      url: '/subIndex/pages_first/_class/class_detail/class_detail?id=' + this.data.chat_ID,
    })
  },
  // 去发布签到
  to_sign_in() {
    wx.navigateTo({
      url: '/subpacks/pages_first/signIn/sign_in',
    })
  },
  //  选择照片
  chooseImg() {
    let _this = this
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album'],
      success(e) {
        // console.log(e.tempFiles[0].tempFilePath);
        _this.setData({
          sendImgUrl: e.tempFiles[0].tempFilePath
        })
        // _this.handleImageUpload(e.tempFiles[0].tempFilePath)
      }
    })
  },
  // 图片上传
  async handleImageUpload(imgUrl) {
    wx.showLoading({
      title: '上传中',
    })
    let imgBase64 = null;
    const fs = wx.getFileSystemManager()
    // 同步接口
    try {
      const res = fs.readFileSync(imgUrl, 'base64', 0)
      console.log("图片的base64：", res)
      imgBase64 = res
    } catch (e) {
      wx.showToast({
        title: e,
      })
    }
    // 分块
    let chunks = splitBase64IntoChunks(imgBase64, 1024 * 64)
    // 删除 "http://"  
    imgUrl = imgUrl.replace("http://", "");
    // // 删除文件的扩展名，包括 "."  
    // imgName = imgName.replace(/\.[^.]+$/, "");

    this.data.socket.send({
      data: JSON.stringify({
        event: 'imgName',
        data: imgUrl
      })
    });

    // 逐个发送块数据
    chunks.forEach((chunk, index) => {
      let eventData = {
        event: 'base64Data', // 事件标识字段
        data: chunk
      };
      setTimeout(() => {
        this.data.socket.send({
          data: JSON.stringify(eventData),
          success: () => {
            console.log(`块 ${index + 1}/${chunks.length} 已发送`);
            if (index === chunks.length - 1) {
              // 所有块数据已发送，发送结束消息
              this.data.socket.send({
                data: JSON.stringify({
                  data: {},
                  event: 'upload_complete'
                }),
                success: () => {
                  console.log('上传完成');
                  // 关闭定时器或执行其他操作
                  wx.hideLoading()
                },
              });
            };
          },
        });
      }, index * 200); // 延迟发送以避免过快发送
    });

  },
  // 打开相机
  open_camera() {
    let _this = this
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['camera'],
      camera: 'back',
      success(e) {
        console.log(e.tempFiles.tempFilePath);
        _this.setData({
          sendImgUrl: e.tempFiles[0].tempFilePath
        })
      }
    })
  },
  // 去投票
  to_vote() {
    wx.navigateTo({
      url: '/subChat/vote/vote?chat_id=' + this.data.chat_ID,
    })
  },
  // 去选投票选项
  toSelectVote(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '../../../subChat/startVoting/startVoting?id=' + id,
    })
  },
  // 去选人
  to_random_sel() {
    wx.navigateTo({
      url: '/subChat/randomSel/random_sel?chat_id=' + this.data.chat_ID,
    })
  },
  // 去选人历史页
  to_random_sel_old() {
    wx.navigateTo({
      url: '/subChat/randomSelOld/random_sel_old?id=' + this.data.chat_ID,
    })
  },
  // 获取班级名字人数
  async getGroupInfo() {
    wx.showLoading({
      title: '加载中',
    })
    try {
      const json = await getApp().$axios('/getGroupChatById?id=' + this.data.chat_ID, "GET")
      wx.hideLoading()
      if (json.status !== 200) {
        wx.showToast({
          title: json.msg,
          icon: 'error'
        })
        return
      }
      // 群聊名字加人数拼接
      console.log(json.data);
      const {
        data,
        count
      } = json.data
      let chatName = `${data.chat_name}(${count})`
      this.setData({
        chatName,
        chat_num: data.chat_num,
        create_id:data.create_userID
      })
      // 初始化socket
      this.initWebsocket();
    } catch (error) {
      wx.showToast({
        title: error.msg,
        icon: 'error'
      })
    }
  },
  // 点击图片预览
  previewImage(e) {
    const urls = e.currentTarget.dataset.url
    wx.previewImage({
      urls: [urls],
    })
  },
  // 发送消息
  sendMsg() {
    // 创建消息对象
    const cahtObj = {
      msg_type: 0,
      msg_content: this.data.key_value
    }
    this.data.socket.send({
      data: JSON.stringify({
        event: 'chat',
        data: {
          user_id: app.userInfo.id,
          chat_num: this.data.chat_num,
          chat_id: this.data.chat_ID,
          content: cahtObj,
          type: 'message'
        }
      })
    })
    this.data.chatRecords.push({
      uid: app.userInfo.id,
      chat_id: this.data.chat_ID,
      user_info: {
        avatar_url: app.userInfo.avatar_url,
        username: app.userInfo.username
      },
      ...cahtObj
    })
    this.setData({
      chatRecords: this.data.chatRecords,
      key_value: null
    })

    wx.createSelectorQuery().select('.chat').boundingClientRect((rect) => {
      this.setData({
        scrollToBottom: rect.height
      })
      console.log('元素的信息 聊天页：', rect);
    }).exec();
  },
  // 聊天记录下拉获取跟多
  async bindrefresherrefresh() {
    this.setData({
      isRefreshing: true
    })
    let params = {
      ...this.data.page,
      chat_ID: this.data.chat_ID
    }
    try {
      const data = await getApp().$axios("/getGroupChatMessage", 'POST', params)
      if (data.status !== 200) {
        wx.showToast({
          title: data.data,
          icon: 'none'
        })
        return
      }
      console.log(data);
      this.data.chatRecords = [...data.data, ...this.data.chatRecords]
      this.setData({
        isRefreshing: false,
        chatRecords: this.data.chatRecords
      })
      if (data.data.length == 0) {
        wx.showToast({
          title: '已经到顶了！',
          icon: 'none'
        })
        return
      }
      this.setData({
        scrollToBottom: 0,
        'page.pageNum': this.data.page.pageNum + 1
      })

    } catch (error) {
      wx.showToast({
        title: error.msg,
        icon: 'error'
      })
    }
  },
  // 去签到页面
  goSignIn(e) {
    const sid = e.currentTarget.dataset.id - 0;
    wx.navigateTo({
      url: '/subpacks/pages_first/faceSignIn/faceSignIn?sid=' + sid,
    })
  },
  // 去选人页
  gosel(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/subChat/selOld/selOld?id=' + id,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let optHeight = app.systemInfo.screenHeight - app.visibleArea - app.systemInfo.statusBarHeight - app.systemInfo.CustomBarHeight;
    let optHeightRpx = 750 / app.systemInfo.windowWidth * optHeight
    this.setData({
      optHeightRpx: optHeightRpx
    });

    // 获取传过来的群聊id
    console.log(options);
    const chat_ID = options.id;
    this.setData({
      chat_ID,
      userId: app.userInfo.id
    })
  },
  // 打开功能列表
  open_func() {
    if (this.data.func_transilate == 0) {
      this.setData({
        chatHeight: 0,
        func_transilate: 400
      })
      return
    }
    this.setData({
      chatHeight: 400,
      func_transilate: 0
    })

  },
  //初始化websocket完整流程
  initWebsocket() {
    const socket = wx.connectSocket({
      url: app.ws,
      success() {
        console.log("socket 服务器连接成功");
      },
      fail() {
        console.log("socket 服务器连接失败");
      }
    });
    this.setData({
      socket
    })
    socket.onOpen(() => {
      console.log('WebSocket 连接已打开');
      // 判断是否选中图片
      if (this.data.sendImgUrl !== null) {
        this.handleImageUpload(this.data.sendImgUrl)
      }
      socket.send({
        data: JSON.stringify({
          event: 'chat',
          data: {
            user_id: app.userInfo.id,
            chat_num: this.data.chat_num,
            chat_id: this.data.chat_ID,
            type: 'join',
          }
        })
      })
    });
    socket.onMessage((res) => {
      const json = JSON.parse(res.data)
      console.log('收到服务器消息json', json);
      // 收到最后十条消息
      if (json.event == "joinSuccess") {
        this.setData({
          chatRecords: json.data.reverse()
        })
        setTimeout(() => {
          wx.createSelectorQuery().select('.chat').boundingClientRect((rect) => {
            this.setData({
              scrollToBottom: rect.height + 60
            })
            // console.log('元素的信息 聊天页：', rect);
          }).exec();
        }, 500)

      }
      // 处理接收到的消息
      if (json.event == "joinFail") {
        // 
        wx.showToast({
          title: json.data,
          icon: 'none'
        })
        // 重新初始化
        this.initWebsocket()
      }
      // 发送错误
      if (json.event == "sendFail") {
        // 消息发送异常
        wx.showToast({
          title: json.data,
          icon: 'none'
        })
        // 删掉数组最后一个然后重新发送
        this.data.chatRecords.splice(this.data.chatRecords.length - 1, 1)
        this.setData({
          chatRecords: this.data.chatRecords
        })
      }
      // 收到别人发送过来的消息
      if (json.event == "message") {
        console.log("收到消息", json.data);
        wx.hideLoading()
        this.data.chatRecords.push(json.data)
        this.setData({
          chatRecords: this.data.chatRecords
        })
        wx.createSelectorQuery().select('.chat').boundingClientRect((rect) => {
          this.setData({
            scrollToBottom: rect.height
          })
          console.log('元素的信息 聊天页：', rect);
        }).exec();
      }
      // 图片地址
      if (json.event == "sentImgUrl") {
        console.log(json.data.imgUrl, "图片在线地址");
        const uploadUrl = 'https://' + json.data.imgUrl
        this.setData({
          uploadUrl
        })
        // 创建消息对象
        const cahtObj = {
          msg_type: 1,
          msg_content: uploadUrl
        }
        this.data.socket.send({
          data: JSON.stringify({
            event: 'chat',
            data: {
              user_id: app.userInfo.id,
              chat_num: this.data.chat_num,
              chat_id: this.data.chat_ID,
              content: cahtObj,
              type: 'message'
            }
          })
        })
        // 把功能栏关掉
        this.setData({
          chatHeight: 0,
          func_transilate: 400,
          sendImgUrl: null
        })
      }
    });

    socket.onClose((res) => {
      console.log('WebSocket 连接已关闭', res);
    });

    socket.onError((res) => {
      console.error('WebSocket 连接出错', res);
    });
  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    console.log(this.data);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getGroupInfo();
    // if (this.data.chat_ID !== null) {
    //   this.initWebsocket()
    // }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    // 关闭连接
    this.data.socket.close()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.data.socket.close()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})